//
//  SafetyCenterViewController.m
//  PetShop
//
//  Created by chirui on 16/11/22.
//  Copyright © 2016年 Shui. All rights reserved.
//

#import "SafetyCenterViewController.h"

@interface SafetyCenterViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
{
    
    UITableView * _tableView;
    NSArray * userPwd;
    NSArray * payForPwd;
    NSString * typeStr;
    UIButton * getBtn;
    UIButton * outBtn;
    
    UIView * lineView_one;
    UIView * lineView_two;
    UIButton * textBtn;
    
    NSString * phoneStr;
    
    UITextField * oldPwdText; // 修改密码
    UITextField * testNumber; //验证码
    UITextField * userPwdText; //新密码
    UITextField * payForText;  // 确认密码
    UITextField * phoneText;   // 联系人
    
    NSArray * phoneArray;
    
    
}

@end

@implementation SafetyCenterViewController

-(void)viewWillDisappear:(BOOL)animated {
    
    self.tabBarController.tabBar.hidden= YES;
}


-(void)viewWillAppear:(BOOL)animated {
    
    self.tabBarController.tabBar.hidden= YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    typeStr =@"1"; // 修改密码
    
    NSString * phone = USER_DEFAULTGet(@"username");
    
    phoneStr =[phone stringByReplacingOccurrencesOfString:[phone substringWithRange:NSMakeRange(3,4)]withString:@"****"];
    
    self.navigationItem.titleView=[TopLabel withLabelWithLabelText:@"安全中心"];
  
    userPwd = @[@"原始密码",@"新密码",@"确认密码"];
    payForPwd = @[@"手机号",@"联系人",@"短信验证码",@"支付密码",@"确认支付密码"];
    [self creatTableView ];
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"icon_nav_renter" target:self action:@selector(backBtnClick)];
    
    [self getUrgentRequest];
}

-(void)backBtnClick{
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)creatTableView {
    
    
    _tableView =[[UITableView alloc]initWithFrame:CGRectMake(0,0, WIDTH, HEIGHT) style:UITableViewStyleGrouped];
    _tableView.delegate=self;
    _tableView.dataSource=self;
    UIView *view = [[UIView alloc]init];
    _tableView.tableFooterView = view;
    
    [self.view addSubview:_tableView];
    
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if ([typeStr isEqualToString:@"1"]) {
         return userPwd.count;
    }else {
        
        return payForPwd.count;
    }
   
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 50;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 55;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {

    return 120;

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString * cellId =@"cellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }else{
        while ([cell.contentView.subviews lastObject]) {
            [[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }

    UILabel * titleStr = [[UILabel alloc]initWithFrame:CGRectMake(10, 15, 100, 20)];
    titleStr.font =[UIFont systemFontOfSize:15];
    if ([typeStr isEqualToString:@"1"]) {
        titleStr.text = userPwd[indexPath.row];
    }else {
        titleStr.text = payForPwd[indexPath.row];
    }
    
    [cell.contentView addSubview:titleStr];
    if ([typeStr isEqualToString:@"1"]) {

        if (indexPath.row==0) {
            
            oldPwdText =[[UITextField alloc]initWithFrame:CGRectMake(110, 15, WIDTH -120, 20)];
            oldPwdText.placeholder = @"请输入原始密码";
            oldPwdText.font =[UIFont systemFontOfSize:15];
            oldPwdText.secureTextEntry = YES;
            [cell.contentView addSubview:oldPwdText];
        }

    }else {
        
        if (indexPath.row==0) {
            
            UILabel * phoneLabel =[[UILabel alloc]initWithFrame:CGRectMake(110, 15, WIDTH -120, 20)];
            phoneLabel.font =[UIFont systemFontOfSize:15];
            phoneLabel.text = phoneStr;
            phoneLabel.textColor = NavBackColor;
            [cell.contentView addSubview:phoneLabel];
            
        }
  
    }
   
    
    if (indexPath.row ==1) {
        
        if ([typeStr isEqualToString:@"1"]) {
            userPwdText =[[UITextField alloc]initWithFrame:CGRectMake(110, 15, WIDTH -120 , 20)];
            userPwdText.placeholder = @"请输入密码";
            userPwdText.font =[UIFont systemFontOfSize:15];
            userPwdText.secureTextEntry = YES;
            if ([typeStr isEqualToString:@"1"]) {
                
                userPwdText.keyboardType = UIKeyboardTypeDefault;
                
            }else {
                
                userPwdText.keyboardType = UIKeyboardTypePhonePad;
            }
            [cell.contentView addSubview:userPwdText];
        }else {
            
            
            phoneText =[[UITextField alloc]initWithFrame:CGRectMake(110, 15, WIDTH -150 , 20)];
            phoneText.placeholder = @"请选择联系人";
            phoneText.font =[UIFont systemFontOfSize:15];
            phoneText.delegate = self;
            [cell.contentView addSubview:phoneText];
            
            UIImageView *   moreImage = [[UIImageView alloc]init];
            moreImage.frame = CGRectMake(WIDTH -30, 15, 25, 25);
            moreImage.image = ImageName(@"icon_user_more");
            [cell.contentView addSubview:moreImage];
            
        }
        
    }

    if (indexPath.row ==2) {
        
        if ([typeStr isEqualToString:@"1"]) {
            payForText =[[UITextField alloc]initWithFrame:CGRectMake(110, 15, WIDTH -120, 20)];
            payForText.placeholder = @"请确认密码";
            payForText.font =[UIFont systemFontOfSize:15];
            payForText.secureTextEntry = YES;
            if ([typeStr isEqualToString:@"1"]) {
                
                payForText.keyboardType = UIKeyboardTypeDefault;
                
            }else {
                
                payForText.keyboardType = UIKeyboardTypePhonePad;
            }
            
            [cell.contentView addSubview:payForText];
        }else {
            
            
            testNumber =[[UITextField alloc]initWithFrame:CGRectMake(110, 15, WIDTH -110 - 100, 20)];
            testNumber.placeholder = @"请输入验证码";
            testNumber.font =[UIFont systemFontOfSize:15];
            [cell.contentView addSubview:testNumber];
            
            textBtn =[UIButton buttonWithType:UIButtonTypeCustom];
            textBtn.frame = CGRectMake(WIDTH -100, 10, 90, 30);
            [textBtn setTitleColor:NavBackColor forState:UIControlStateNormal];
            [textBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
            //        textBtn.layer.cornerRadius = 15;
            //        textBtn.layer.masksToBounds =YES;
            //        textBtn.layer.borderWidth = 1;
            textBtn.titleLabel.font =[UIFont systemFontOfSize:15];
            textBtn.layer.borderColor = NavBackColor.CGColor;
            [textBtn addTarget:self action:@selector(textBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            [cell.contentView addSubview:textBtn];
     
            
        }
        
    }
    if ([typeStr isEqualToString:@"2"]) {
        
        if (indexPath.row ==3) {
            
            userPwdText =[[UITextField alloc]initWithFrame:CGRectMake(110, 15, WIDTH -120 , 20)];
            userPwdText.placeholder = @"请输入密码";
            userPwdText.font =[UIFont systemFontOfSize:15];
            userPwdText.secureTextEntry = YES;
            if ([typeStr isEqualToString:@"1"]) {
                
                userPwdText.keyboardType = UIKeyboardTypeDefault;
                
            }else {
                
                userPwdText.keyboardType = UIKeyboardTypePhonePad;
            }
            [cell.contentView addSubview:userPwdText];
            
           
        }
        if (indexPath.row==4) {
            
            payForText =[[UITextField alloc]initWithFrame:CGRectMake(110, 15, WIDTH -120, 20)];
            payForText.placeholder = @"请确认密码";
            payForText.font =[UIFont systemFontOfSize:15];
            payForText.secureTextEntry = YES;
            if ([typeStr isEqualToString:@"1"]) {
                
                payForText.keyboardType = UIKeyboardTypeDefault;
                
            }else {
                
                payForText.keyboardType = UIKeyboardTypePhonePad;
            }
            
            [cell.contentView addSubview:payForText];
        }
    }
    

    return cell;
}

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    
    if (textField == phoneText) {
        [textField resignFirstResponder];
        
        zySheetPickerView * pickerView = [zySheetPickerView ZYSheetStringPickerWithTitle:phoneArray andHeadTitle:@"选择联系人" Andcall:^(zySheetPickerView *pickerView, NSString *choiceString) {
            phoneText.text = choiceString;
           
            [pickerView dismissPicker];
        }];
        [pickerView show];
    }
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView * heardView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 55)];
    heardView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    UIView * topView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 45)];
   
    topView.backgroundColor =[UIColor whiteColor];
    [heardView addSubview:topView];
    
    lineView_one =[[UIView alloc]initWithFrame:CGRectMake(20, 43, WIDTH/2-40, 2)];
    lineView_one.backgroundColor = NavBackColor;
    lineView_one.hidden = YES;
    [topView addSubview:lineView_one];
    
    lineView_two =[[UIView alloc]initWithFrame:CGRectMake(WIDTH/2+20, 43, WIDTH/2-40, 2)];
    lineView_two.backgroundColor = NavBackColor;
    lineView_two.hidden = YES;
    [topView addSubview:lineView_two];
    
    getBtn =[UIButton buttonWithType:UIButtonTypeSystem];
    getBtn.frame = CGRectMake(0, 0, WIDTH/2, 43);
    [getBtn setTitle:@"修改登录密码" forState:UIControlStateNormal];
    
     getBtn.titleLabel.font =[UIFont systemFontOfSize:16];
    [getBtn addTarget:self action:@selector(changePwd:) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:getBtn];
    
    outBtn =[UIButton buttonWithType:UIButtonTypeSystem];
    outBtn.frame = CGRectMake(WIDTH/2, 0, WIDTH/2, 43);
    [outBtn setTitle:@"设置支付密码" forState:UIControlStateNormal];
    if ([typeStr isEqualToString:@"1"]) {
        [getBtn setTitleColor:NavBackColor forState:UIControlStateNormal];
        [outBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        lineView_one.hidden = NO;
        lineView_two.hidden = YES;
        
    }else {
    
        [outBtn setTitleColor:NavBackColor forState:UIControlStateNormal];
        [getBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        lineView_one.hidden = YES;
        lineView_two.hidden = NO;
    }
    
    outBtn.titleLabel.font =[UIFont systemFontOfSize:16];
    [outBtn addTarget:self action:@selector(changePayForPwd:) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:outBtn];
    
    return heardView;
}


-(void)textBtnClick:(UIButton *)btn {

    
    if (phoneText.text.length !=11) {
        
        [SHJudgeTools MBProgressHUDPromptWith:@"请选择联系人" On:self.view];
        return;
        
    }
    [self sendMSNetWorkingFor];
    __block int timeout = 60; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=1){
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                

                [textBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                textBtn.userInteractionEnabled = YES;
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                
                NSString  * time = [NSString stringWithFormat:@"%d(秒)",timeout];
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDuration:1];
                [textBtn setTitle:time forState:UIControlStateNormal];
                [UIView commitAnimations];
                textBtn.userInteractionEnabled = NO;
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
    
}

// 验证码
-(void)sendMSNetWorkingFor{
    
    NSString * parametersStr = [NSString stringWithFormat:@"%@%@",address_url,user_signup_code_api];
    NSDictionary * parameter = @{@"username":phoneText.text,
                                 @"type":@"pay"
                                 };
    NSLog(@"param ==%@",parameter);
    
    SHuiMBhubNoTimeStr(@"正在发送");
    [PostNetWorking postNetWorkingStr:parametersStr  andparameters:parameter  Success:^(id responseObject) {
        SHuiMBHidleYes;
        if ([responseObject[@"code"] intValue]==200) {
            SHuiMBhudTextTimeStr(@"发送成功");
            
        } else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
    } failed:^(NSError *error) {
        
        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"请检查您的网络!");
    }];
}

-(void)changePayForPwd:(UIButton *)btn {

    typeStr=@"2";
    [_tableView reloadData];
    
}

-(void)changePwd:(UIButton *)btn {
    
     typeStr=@"1";
    
     [_tableView reloadData];
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {

    UIView * footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 120)];
//    footerView.backgroundColor = Color(250,255,253);
    
    UIButton * sureBtn =[UIButton buttonWithType:UIButtonTypeSystem];
    sureBtn.frame = CGRectMake((WIDTH-300)/2, 20,300, 80);
    [sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    sureBtn.layer.cornerRadius = 20.f;
    sureBtn.layer.masksToBounds =YES;
 
    [sureBtn setBackgroundImage:ImageName(@"icon_login__buttton_bg")forState:UIControlStateNormal];
    sureBtn.titleLabel.font =[UIFont systemFontOfSize:16];
    [sureBtn addTarget:self action:@selector(sureBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:sureBtn];

    return footerView;
}

-(void)sureBtnClick:(UIButton *)btn {

    if ([typeStr isEqualToString:@"1"]) {
        
        if (oldPwdText.text==nil||oldPwdText.text.length<1) {
            
            [SHJudgeTools MBProgressHUDPromptWith:@"请输入原密码" On:self.view];
            
            return;
        }
        if (userPwdText.text==nil||userPwdText.text.length<1) {
            
            [SHJudgeTools MBProgressHUDPromptWith:@"请输入新密码" On:self.view];
            
            return;
        }
        if (payForText.text==nil||payForText.text.length<1) {
            
            [SHJudgeTools MBProgressHUDPromptWith:@"请输入确认密码" On:self.view];
            
            return;
        }
        if (![payForText.text isEqualToString:userPwdText.text]) {
            
            [SHJudgeTools MBProgressHUDPromptWith:@"两次密码不一致" On:self.view];
            
            return;
        }
        
        [self ChangePasswordNetWorking];
        
        
    }else {
        
        
        if (phoneText.text==nil||phoneText.text.length<1) {
            
            [SHJudgeTools MBProgressHUDPromptWith:@"请输选择联系人" On:self.view];
            
            return;
        }
        
        if (testNumber.text==nil||testNumber.text.length<1) {
            
            [SHJudgeTools MBProgressHUDPromptWith:@"请输入验证码" On:self.view];
            
            return;
        }
    
        if (testNumber.text==nil||testNumber.text.length<1) {
            
            [SHJudgeTools MBProgressHUDPromptWith:@"请输入验证码" On:self.view];
            
            return;
        }
        if (userPwdText.text==nil||userPwdText.text.length!=6) {
            
            [SHJudgeTools MBProgressHUDPromptWith:@"支付密码只能为六位" On:self.view];
            
            return;
        }
        if (payForText.text==nil||payForText.text.length!=6) {
            
            [SHJudgeTools MBProgressHUDPromptWith:@"支付密码只能为六位" On:self.view];
            
            return;
        }
        if (![payForText.text isEqualToString:userPwdText.text]) {
            
            [SHJudgeTools MBProgressHUDPromptWith:@"两次密码不一致" On:self.view];
            
            return;
        }
        
        [self setPayForPwdNetWorking];
    }

}
// 修改登录密码
-(void)ChangePasswordNetWorking{
    
    NSString * parametersStr = [NSString stringWithFormat:@"%@%@",address_url,safty_modifyLoginPwd_api];
    NSDictionary * parameter = @{
                                 @"username":USER_DEFAULTGet(@"username"),
                                 @"oldPwd":oldPwdText.text,
                                 @"newPwd":userPwdText.text
                                 };
    NSLog(@"param ==%@",parameter);
    
    SHuiMBhubNoTimeStr(@"正在修改...");
    [PostNetWorking postNetWorkingStr:parametersStr  andparameters:parameter  Success:^(id responseObject) {
        
        SHuiMBHidleYes;
        if ([responseObject[@"code"] intValue]==200) {
            SHuiMBhudTextTimeStr(@"修改成功，请重新登录");
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                
                USER_DEFAULTSet(@"", @"token");
                USER_DEFAULTSet(@"", @"enter");
                USER_DEFAULTSet(@"", @"tokenVerify");
                USER_DEFAULTSet(@"", @"user_id");
                USER_DEFAULTSet(@"", @"pay_pwd");
                USER_DEFAULTSet(@"", @"username");
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW , (1 * NSEC_PER_SEC)), dispatch_get_main_queue(),^{
                    LoginAndSignUpVC * loging = [[LoginAndSignUpVC alloc]init];
                    loging.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:loging animated:YES];
                });
            });
        } else {
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
    } failed:^(NSError *error) {
        
        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"请检查您的网络!");
    }];
}

-(void)setPayForPwdNetWorking{
    
    NSString * parametersStr = [NSString stringWithFormat:@"%@%@",address_url,safty_modifyPayPwd_api];
    NSDictionary * parameter = @{@"mid":USER_DEFAULTGet(@"mid"),
                                 @"token":USER_DEFAULTGet(@"token"),
                                 @"username":USER_DEFAULTGet(@"username"),
                                 @"code":testNumber.text,
                                 @"paypwd":payForText.text,
                                 @"contact":phoneText.text
                                 };
    NSLog(@"param ==%@",parameter);
    
    SHuiMBhubNoTimeStr(@"正在加载...");
    [PostNetWorking postNetWorkingStr:parametersStr  andparameters:parameter  Success:^(id responseObject) {
        SHuiMBHidleYes;
        if ([responseObject[@"code"] intValue]==200) {
            SHuiMBhudTextTimeStr(@"设置成功");
            
            USER_DEFAULTSet(@"1", @"blanceStaits");
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW , (1 * NSEC_PER_SEC)), dispatch_get_main_queue(),^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
            });
        } else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
    } failed:^(NSError *error) {
        
        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"请检查您的网络!");
    }];
}

-(void)getUrgentRequest{
    
    NSDictionary * dic = @{@"username":USER_DEFAULTGet(@"username")
                           };
    [PostNetWorking postNetWorkingStr:RequestUrlStr(get_urgentPhone_api) andparameters:dic Success:^(id responseObject) {
        if (codeSucess) {
            
            NSString * str  = responseObject[@"datas"][@"contact_1"];
            if (str ==nil||str.length<=0) {
                
                phoneArray  = @[USER_DEFAULTGet(@"username")];
                
            }else {
                
                phoneArray  = @[responseObject[@"datas"][@"contact_1"],responseObject[@"datas"][@"contact_2"],USER_DEFAULTGet(@"username")];
            }
            
            
        }else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
    } failed:^(NSError *error) {
        SHuiMBhudTextNetError;
    }];
    
    
}


@end
